function EEG = cvc_prepare_spm(EEG)
% cvc_prepare_bdf - Make the channel/fiducial location files for SPM
%
% synopsis:
%
%   EEG = cvc_prepare_spm(EEG)
%
% input:
%
%   EEG : the EEGLAB structure with the '.cvc' field (see CVC_LOAD_BDF).
%
% output:
%
%   Two mat files are written to the disc. The filenames are
%   [EEG.filepath EEG.filename _cvcchanlocs] and
%   [EEG.filepath EEG.filename _cvcfidlocs], these can be used
%   with SPM (see XXXXXX)
%
% example:
%
%   
% Authors: Mads Dyrholm and Carsten Stahlhut, 2009

M=1;
for ch = 1:length(EEG.chanlocs)
  urch = find(strcmp({EEG.cvc.elpchanlocs.labels},EEG.chanlocs(ch).labels));
  if (~isempty(urch))
    tmp = EEG.cvc.elpchanlocs(urch);
    spmlocs(M,:) = [tmp.X, tmp.Y, tmp.Z];
    M = M + 1;
  end
end
[pp,nn,ee] = fileparts(EEG.filename);
pp = EEG.filepath;

for fidx=1:3
  spmfids(fidx,:) = [EEG.cvc.elpfidlocs(fidx).X, EEG.cvc.elpfidlocs(fidx).Y, EEG.cvc.elpfidlocs(fidx).Z];
end
locsfile = fullfile(pp,[nn '_cvcchanlocs'])
fidsfile = fullfile(pp,[nn '_cvcfidlocs'])
EEG.cvc.locsfile = locsfile;
EEG.cvc.fidsfile = fidsfile;
save(locsfile,'spmlocs');
save(fidsfile,'spmfids');
